import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;


public class Server implements Runnable{
	private int port;
	private Thread thread;
	
	public Server(){
		this(1445);
	}
	
	public Server(int port){
		this.port = port;
	}
	
	public void start(){
		if(thread == null){
			thread = new Thread(this);
			thread.start();
		}
	}
	
	public void stop(){
		thread = null;
	}

	@Override
	public void run() {
		ServerSocket serverSocket = null;
		Controller controller = new Controller();
		try {
			serverSocket = new ServerSocket(port);
			serverSocket.getInetAddress();
			System.out.println("Server started:" + InetAddress.getLocalHost() + ":" + port);
			while(thread == Thread.currentThread()){
				Socket socket = serverSocket.accept();
				System.out.println("New Connection from: " + socket.getInetAddress().getHostAddress());
				new Client(socket, controller).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(serverSocket != null){
				try {
					serverSocket.close();
				} catch (IOException e) {}
			}
		}
	}
	
	public static void main(String[] arg){
		new Server(1445).start();
	}

}
